package de.ohmhochschule.bme;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View {

	private final GameActivity game;

	private float width;
	private float height;

	public GameView(Context context) {
		super(context);
		this.game = (GameActivity) context;
		setFocusable(true);
		setFocusableInTouchMode(true);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		width = w / 3f;
		height = h / 3f;
		super.onSizeChanged(w, h, oldw, oldh);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		setBackgroundColor(Color.WHITE);

		// draw the grid:
		Paint gridColor = new Paint();
		gridColor.setStrokeWidth(2);
		gridColor.setColor(Color.BLACK);
		for (int i = 0; i < 3; i++) {
			canvas.drawLine(0, i * height, getWidth(), i * height, gridColor);
		}
		for (int i = 0; i < 3; i++) {
			canvas.drawLine(i * width, 0, i * width, getHeight(), gridColor);
		}

		// draw the 'X' and 'O':
		Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
		foreground.setColor(Color.RED);
		foreground.setStyle(Style.FILL);
		foreground.setTextSize(height * 0.75f);
		foreground.setTextScaleX(width / height);
		foreground.setTextAlign(Paint.Align.CENTER);

		FontMetrics fm = foreground.getFontMetrics();
		float x = width / 2;
		float y = height / 2 - (fm.ascent + fm.descent) / 2;

		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				canvas.drawText("" + this.game.getData(i, j), i * width + x, j
						* height + y, foreground);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() != MotionEvent.ACTION_DOWN) {
			return super.onTouchEvent(event);
		}
		game.setNewPosition((int) (event.getX() / width),
				(int) (event.getY() / height));
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int position = keyCode - KeyEvent.KEYCODE_1;
		if ((position >= 0) && (position <= 9)) {
			game.setNewPosition(position);
		} else {
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}
}
